package com.itchu.auth.controller;

import com.itchu.auth.service.AuthService;
import com.itchu.system.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Controller
@RequestMapping("/api")
public class AuthController {

    @Autowired
    private AuthService authService;


    /**
     * 登录操作
     *
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/login")
    public ResponseEntity<Void> login(
            @RequestParam(value = "username") String username,
            @RequestParam(value = "password") String password,
            HttpServletResponse response
    ) {

        authService.login(username, password, response);
        System.out.println("登录成功了，写入cookie2");
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    /**
     * 认证业务
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/verify")
    public ResponseEntity<User> verify(HttpServletRequest request, HttpServletResponse response) {
        User user = authService.verify(request,response);
        return ResponseEntity.ok(user);
    }

    /**
     * 从cookie中解析出载荷，并返回用户信息
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/VerifySysUser")
    public ResponseEntity<Map<String, Object>> getVerifyUser (HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = authService.getVerifyUser(request,response);
        return ResponseEntity.ok(map);
    }

    /**
     * 退出登录
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/logout")
    public ResponseEntity<Boolean> logout(HttpServletRequest request, HttpServletResponse response) {

        Boolean b = authService.logout(request,response);
        return ResponseEntity.ok(b);
    }
}